# 导入中间件的父类
import requests
from django.http import JsonResponse, HttpResponse
from django.utils.deprecation import MiddlewareMixin
from lxml import etree
from xpinyin import Pinyin

ips = []
p = Pinyin()


class TestMiddleware1(MiddlewareMixin):
    """自定义中间件"""

    def process_request(self, request):
        """处理请求前自动调用"""
        if request.META.get('HTTP_X_FORWARDED_FOR'):
            ip = request.META.get("HTTP_X_FORWARDED_FOR")
        else:
            ip = request.META.get("REMOTE_ADDR")

        # data = {"ip": ip}

        if ip in ips:
            return JsonResponse({"salute": "Sorry, you do not have permission to access in your area"})

        url = "https://ip38.com/ip.php?ip=%s" % ip
        headers = {
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.104 Safari/537.36"
        }
        resp = requests.post(url=url, headers=headers)
        xhtml = etree.HTML(resp.text)

        addr = xhtml.xpath('//*[@id="c"]/font[1]/font[2]/text()')[0]
        addr = p.get_pinyin(addr, '')
        ret = ['hebeisheng', 'shanxisheng', 'pingyuansheng', 'suiyuansheng', 'chahaersheng', 'liaodongsheng',
               'liaoxisheng', 'jilinsheng', 'heilongjiangsheng', 'songjiangsheng', 'rehesheng', 'shanxisheng',
               'gansusheng', 'ningxiasheng', 'qinghaisheng', 'xinjiangsheng', 'shandongsheng', 'fujiansheng',
               'zhejiangsheng', 'henansheng', 'hubeisheng', 'hunansheng', 'jiangxisheng', 'guangdongsheng',
               'guangxisheng', 'guizhousheng', 'yunnansheng', 'xikangsheng', 'beijingshi', 'tianjinshi',
               'zhongqingshi', 'shanghaishi', 'shenyangshi', 'fushunshi', 'anshanshi', 'benxishi', 'xianshi',
               'nanjingshi', 'wuhanshi', 'guangzhoushi', "jiangsusheng"]

        # ret = list(map(lambda x: p.get_pinyin(x, ""), reli))
        for i in ret:
            if i.replace("sheng", "").replace("shi", "") in addr:
                ips.append(ip)
                return JsonResponse({"salute": "Sorry, you do not have permission to access in your area"})

    def process_view(self, request, view_func, view_args, view_kwargs):
        # 处理视图前自动调用
        pass
